package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.entity.Employee;
import org.example.entity.User;
import org.example.entity.UserDept;
import org.example.models.R;
import org.example.service.*;
import org.example.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/system/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    UserDeptService userDeptService;
    @Autowired
    UserPostService userPostService;
    @Autowired
    EmployeeService employeeService;

    @PostMapping("/login")
    public R login(String username, String password) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.lambda().eq(User::getUsername, username);
        query.lambda().eq(User::getPassword, password);

        User users = userService.getOne(query);

        if (users == null) {
            return R.error(401, "登陆失败，用户名或账户错误。");
        }
        String token = JwtUtils.generateToken(users.getUserId(), users.getUsername());
        UserDept userInformation = userDeptService.findUserInformation(users.getUserId());
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", userInformation);

        return R.success(200, "登录成功", result);
    }

    @PostMapping("/log")
    public R log(String username, String password, HttpSession session) {  // 添加HttpSession参数
        QueryWrapper<Employee> query = new QueryWrapper<>();

        query.lambda().eq(Employee::getEmployeeName, username);
        query.lambda().eq(Employee::getLoginPassword, password);

        Employee employee = employeeService.getOne(query);

        if (employee == null) {
            return R.error(401, "登陆失败，用户名或账户错误。");
        }

        String token = JwtUtils.generateToken(employee.getEmployeeId(), employee.getEmployeeName());
        Employee emp = employeeService.findEmpAndDept(employee.getEmployeeId());

        // 将数据存入session
        session.setAttribute("token", token);
        session.setAttribute("user", emp);

        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", emp);
        return R.success(200, "登录成功", result);
    }


    //    新增用户
    @PostMapping("/insert")
    public R add() {
        return R.success(userService);
    }
}
